<template>
    <div class="app-container">
        <div class="head">
            <img src="@/assets/img/Layout/position.png" />
            <p class="see-block">采购退货新建</p>
        </div>
        <div class="view-container">
            <el-row class="status-title">
                <el-col class="mr20 width100">
                    <el-button
                        class="btn-success width100"
                        type="primary"
                        @click="submitForm('save')"
                    >保存</el-button>
                </el-col>
                <el-col class="mr20 width100">
                    <el-button
                        class="btn-success width100"
                        type="primary"
                        @click="submitForm('submit')"
                    >提交</el-button>
                </el-col>
                <!-- <el-col :span="10" class="status-container">
                    <div class="status-item">
                        <span class="active">草稿</span>
                        <span>待审核</span>
                        <span>已审核</span>
                        <span>拒绝</span>
                    </div>
                </el-col> -->
            </el-row>
            <el-form ref="form" :model="form" label-width="100px" class="mt30">
                <el-row>
                    <el-col :span="9">
                        <el-form-item label="采购退货编码:" prop="code">
                            <el-input v-model="form.code" placeholder="系统自动生成" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="9">
                        <el-form-item label="业务日期:" prop="businessDate">
                            <el-input v-model="form.businessDate" placeholder="系统自动生成，获取当前日期时间" disabled />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="9">
                        <el-form-item label="供应商名称:" prop="supplierName">
                            <el-input v-model="form.supplierName" placeholder="输入名称或代码模糊搜索" style="width:82%;" @input="onChangeSupplier" />
                            <ul class="options" v-if="show" >
                                <div class="options-item" v-if="supplierList.length > 0">
                                    <li @click="check(item)" v-for="item in supplierList" :key="item.id">
                                        {{ item.name }}
                                    </li>
                                </div>
                            </ul>
                            <el-button type="primary" size="small" class="btn-success" icon="el-icon-search" style="position:absolute;right:0;top:0;bottom:0;width:15%;font-size:14px;" @click="onSupplierList"></el-button>
                        </el-form-item>
                    </el-col>
                    <el-col :span="9">
                        <el-form-item label="要求退货:" prop="returnDate">
                            <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" v-model="form.returnDate" suffix-icon="el-icon-date" type="datetime" placeholder="采购期望日期" style="width:100%;" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="9">
                        <el-form-item label="业务模式:" prop="businessModel">
                            采购退货
                        </el-form-item>
                    </el-col>
                    <el-col :span="9">
                        <el-form-item label="业务部门:" prop="businessUnit">
                            <el-select v-model="form.businessUnit" style="width:100%;" placeholder="请选择">
                                <!-- <el-option label="采购部" value="1">采购部</el-option>
                                <el-option label="销售部" value="2">销售部</el-option> -->
                                <el-option
                                    v-for="item in businessUnitList"
                                    :key="item.deptId"
                                    :label="item.deptName"
                                    :value="item.deptName">
                                </el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="9">
                        <el-form-item label="是否有源单:" prop="haveOrNot">
                            <el-radio-group v-model="form.haveOrNot" @change="onChangeIs">
                                <el-radio label="1">是</el-radio>
                                <el-radio label="0">否</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="9" v-if="form.haveOrNot == '1'">
                        <el-form-item label="是否全退:" prop="allOrNot">
                            <el-radio-group v-model="form.allOrNot" @change="onChangeIsAllReturn">
                                <el-radio label="1">是</el-radio>
                                <el-radio label="0">否</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-if="form.haveOrNot == '1'">
                    <el-col :span="9">
                        <template v-if="purchaseOrderList.length > 0">
                            <el-form-item label="源采购订单:" prop="purchaseOrderCode">
                                <el-select v-model="form.purchaseOrderCode" style="width:82%;" placeholder="请选择" @change="onChangePurchaseOrder">
                                    <el-option
                                        v-for="item in purchaseOrderList"
                                        :key="item.id"
                                        :label="item.purchaseOrderCode"
                                        :value="item.purchaseOrderCode">
                                    </el-option>
                                </el-select>
                                <el-button type="primary" size="small" class="btn-success" icon="el-icon-search" style="position:absolute;right:0;top:0;bottom:0;width:15%;font-size:14px;" @click="onPurchaseOrderList"></el-button>
                            </el-form-item>
                        </template>
                        <template v-else>
                            <el-form-item label="源采购订单:" prop="purchaseOrderCode">
                                <el-input v-model="form.purchaseOrderCode" placeholder="暂无" disabled />
                            </el-form-item>
                        </template>
                    </el-col>
                    <el-col :span="9">
                        <el-form-item label="退货原因:" prop="reasonForReturn">
                            <el-input v-model="form.reasonForReturn" placeholder="" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="9">
                        <el-form-item label="发票类型:" prop="invoiceType">
                            <el-select v-model="form.invoiceType" placeholder="请选择" style="width:100%;">
                                <el-option label="普通发票" value="1">普通发票</el-option>
                                <el-option label="增值税发票" value="2">增值税发票</el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="9">
                        <el-form-item label="备注:" prop="remark">
                            <el-input v-model="form.remark" placeholder="" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-table :data="productData">
                            <el-table-column label="序号" type="index" align="center" width="50" />
                            <el-table-column :label="item.label" :prop="item.prop" :width="item.width" v-for="(item, index) in columns" :key="index" align="center">
                                <template slot-scope="scope">
                                    <template v-if="item.type == '1'">
                                        <template v-if="form.haveOrNot == '1'">
                                            <template v-if="form.allOrNot == '1'">
                                                {{ scope.row[item.prop] }}
                                            </template>
                                            <template v-else>
                                                <el-autocomplete
                                                    v-model="scope.row[item.prop]"
                                                    :fetch-suggestions="searchCode"
                                                    placeholder="请输入产品编码"
                                                    @select="val => handleSelect(val, scope.row, scope.$index)"
                                                ></el-autocomplete>
                                            </template>
                                        </template>
                                        <template v-else>
                                            <el-autocomplete
                                                style="width:74%;margin-right:5px;"
                                                v-model="scope.row[item.prop]"
                                                :fetch-suggestions="searchProductCode"
                                                placeholder="请输入产品编码"
                                                @select="val => handleSelect(val, scope.row, scope.$index)"
                                            ></el-autocomplete>
                                            <el-button type="primary" size="small" class="btn-success" icon="el-icon-search" @click="searchProductSku(scope.$index)"></el-button>
                                        </template>
                                    </template>
                                    <template v-if="item.type == '2'">
                                        <template v-if="form.haveOrNot == '1'">
                                            <template v-if="form.allOrNot == '1'">
                                                {{ scope.row[item.prop] }}
                                            </template>
                                            <template v-else>
                                                <el-autocomplete
                                                    v-model="scope.row[item.prop]"
                                                    :fetch-suggestions="searchName"
                                                    placeholder="请输入产品名称"
                                                    @select="val => handleSelect(val, scope.row, scope.$index)"
                                                ></el-autocomplete>
                                            </template>
                                        </template>
                                        <template v-else>
                                            <el-autocomplete
                                                style="width:74%;margin-right:5px;"
                                                v-model="scope.row[item.prop]"
                                                :fetch-suggestions="searchProductName"
                                                placeholder="请输入产品名称"
                                                @select="val => handleSelect(val, scope.row, scope.$index)"
                                            ></el-autocomplete>
                                            <el-button type="primary" size="small" class="btn-success" icon="el-icon-search" @click="searchProductSku(scope.$index)"></el-button>
                                        </template>
                                    </template>
                                    <template v-if="item.type == 'batchNumber'">
                                        <template v-if="form.haveOrNot == '1'">
                                            {{ scope.row[item.prop] }}
                                        </template>
                                        <template v-else>
                                            <template v-if="scope.row.enableBatches == '0'">
                                                <el-select v-model="scope.row[item.prop]" placeholder="请选择" @change="val => onChangeBatch(val, scope.row)">
                                                    <el-option
                                                        v-for="item in purchaseOrderBatch"
                                                        :key="item.specificationId"
                                                        :label="item.batchNumber"
                                                        :value="item.batchNumber">
                                                    </el-option>
                                                </el-select>
                                            </template>
                                            <template v-else>
                                                {{ scope.row[item.prop] }}
                                            </template>
                                        </template>
                                    </template>
                                    <template v-if="item.type == 'planNum'">
                                        <el-input placeholder="请输入数量" v-model="scope.row[item.prop]" @input="(val) => inputNum(val, scope.row)" />
                                    </template>
                                    <!-- <template v-if="item.type == 'isGift'">
                                        <template v-if="form.haveOrNot == '1'">
                                            <el-checkbox v-model="scope.row[item.prop]" disabled></el-checkbox>
                                        </template>
                                        <template v-else>
                                            <el-checkbox v-model="scope.row[item.prop]"></el-checkbox>
                                        </template>
                                    </template> -->
                                    <!-- <template v-if="item.type == 'arrivalDate'">
                                        <template v-if="form.haveOrNot == '1'">
                                            {{ scope.row[item.prop] }}
                                        </template>
                                        <template v-else>
                                            <el-date-picker value-format="yyyy-MM-dd HH:mm:ss" v-model="scope.row[item.prop]" suffix-icon="el-icon-date" type="datetime" placeholder="到货日期" :picker-options="pickerOptions" style="width:100%;"></el-date-picker>
                                        </template>
                                    </template> -->
                                    <template v-if="item.type == '3'">{{ scope.row[item.prop] }}</template>
                                    <template v-if="item.type == 'remark'">
                                        <template v-if="form.haveOrNot == '1'">
                                            {{ scope.row[item.prop] }}
                                        </template>
                                        <template v-else>
                                            <el-input placeholder="" v-model="scope.row[item.prop]" />
                                        </template>
                                    </template>
                                </template>
                            </el-table-column>
                        </el-table>
                    </el-col>
                </el-row>
                <el-row class="mt20">
                    <el-col :span="8">
                        <el-form-item label="合计数量:" prop="totalNum">
                            <el-input v-model="form.totalNum" placeholder="系统自动合计" disabled />
                        </el-form-item>
                    </el-col>
                    <!-- <el-col :span="8">
                        <el-form-item label="合计未税金额:" prop="totalAmount">
                            <el-input v-model="form.totalAmount" placeholder="系统自动合计" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="合计价税合计:" prop="totalTaxAmount">
                            <el-input v-model="form.totalTaxAmount" placeholder="系统自动合计" disabled />
                        </el-form-item>
                    </el-col> -->
                </el-row>
            </el-form>
        </div>
        <el-dialog :visible.sync="open" width="100%" top="50px" title="采购订单" center>
            <el-row>
                <el-col :span="24">
                    <el-form :model="queryParams" ref="queryForm" :inline="true" @submit.native.prevent>
                        <el-form-item prop="searchValue">
                            <el-input
                                v-model="queryParams.searchValue"
                                placeholder=""
                                clearable
                                size="small"
                                @keyup.enter.native="handleQuery"
                            />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery" class="list-search btn-success" color="#5ED4D4">搜索</el-button>
                            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery" class="list-search">重置</el-button>
                        </el-form-item>
                    </el-form>
                </el-col>
                <el-col :span="24">
                    <el-table :data="queryPurchaseOrderList" @row-click="onClickPurchaseOrderList">
                        <el-table-column label="序号" type="index" align="center" width="50">
                        <template slot-scope="scope">
                            <span>{{(queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1}}</span>
                        </template>
                        </el-table-column>
                        <el-table-column label="订单编码"  align="center" prop="purchaseOrderCode" width="180px" />
                        <el-table-column label="供应商"  align="center" prop="supplierName" :show-overflow-tooltip="true" width="100px" />
                        <el-table-column label="产品编码" align="center" prop="productCode" :show-overflow-tooltip="true" width="150px">
                        <template slot-scope="scope">
                            <div v-for="(item, index) in scope.row.purchaseOrderProductList" :key="index" class="item">
                            {{ item.productBasicCode }}
                            </div>
                        </template>
                        </el-table-column>
                        <el-table-column label="产品名称" align="center" prop="productName" :show-overflow-tooltip="true" width="150px">
                        <template slot-scope="scope">
                            <div v-for="(item, index) in scope.row.purchaseOrderProductList" :key="index" class="item">
                            {{ item.productBasicName }}
                            </div>
                        </template>
                        </el-table-column>
                        <el-table-column label="SKU编码" align="center" prop="productCode" :show-overflow-tooltip="true" width="150px">
                        <template slot-scope="scope">
                            <div v-for="(item, index) in scope.row.purchaseOrderProductList" :key="index" class="item">
                            {{ item.productCode }}
                            </div>
                        </template>
                        </el-table-column>
                        <el-table-column label="SKU名称" align="center" prop="productName" :show-overflow-tooltip="true" width="150px">
                        <template slot-scope="scope">
                            <div v-for="(item, index) in scope.row.purchaseOrderProductList" :key="index" class="item">
                            {{ item.productName }}
                            </div>
                        </template>
                        </el-table-column>
                        <el-table-column label="简称" align="center" prop="productShortName" :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <div v-for="(item, index) in scope.row.purchaseOrderProductList" :key="index" class="item">
                            {{ item.productShortName }}
                            </div>
                        </template>
                        </el-table-column>
                        <el-table-column label="规格" align="center" prop="specification" :show-overflow-tooltip="true" width="150px">
                        <template slot-scope="scope">
                            <div v-for="(item, index) in scope.row.purchaseOrderProductList" :key="index" class="item">
                            {{ item.specification }}
                            </div>
                        </template>
                        </el-table-column>
                        <el-table-column label="批号" align="center" prop="batch" :show-overflow-tooltip="true" width="150px">
                        <template slot-scope="scope">
                            <div v-for="(item, index) in scope.row.purchaseOrderProductList" :key="index" class="item">
                            {{ item.batch }}
                            </div>
                        </template>
                        </el-table-column>
                        <el-table-column label="数量" align="center" prop="num" :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <div v-for="(item, index) in scope.row.purchaseOrderProductList" :key="index" class="item">
                            {{ item.num }}
                            </div>
                        </template>
                        </el-table-column>
                        <el-table-column label="单位" align="center" prop="unit" :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <div v-for="(item, index) in scope.row.purchaseOrderProductList" :key="index" class="item">
                            {{ item.unit }}
                            </div>
                        </template>
                        </el-table-column>
                        <el-table-column label="未税单价" align="center" prop="untaxedAmount" :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <div v-for="(item, index) in scope.row.purchaseOrderProductList" :key="index" class="item">
                            {{ item.untaxedAmount }}
                            </div>
                        </template>
                        </el-table-column>
                        <el-table-column label="金额" align="center" prop="amount" :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <div v-for="(item, index) in scope.row.purchaseOrderProductList" :key="index" class="item">
                            {{ item.amount }}
                            </div>
                        </template>
                        </el-table-column>
                        <el-table-column label="税率" align="center" prop="taxRate" :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <div v-for="(item, index) in scope.row.purchaseOrderProductList" :key="index" class="item">
                            {{ item.taxRate }}
                            </div>
                        </template>
                        </el-table-column>
                        <el-table-column label="税款" align="center" prop="levy" :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <div v-for="(item, index) in scope.row.purchaseOrderProductList" :key="index" class="item">
                            {{ item.levy }}
                            </div>
                        </template>
                        </el-table-column>
                        <el-table-column label="价税合计" align="center" prop="totalTax" :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <div v-for="(item, index) in scope.row.purchaseOrderProductList" :key="index" class="item">
                            {{ item.totalTax }}
                            </div>
                        </template>
                        </el-table-column>
                        <el-table-column label="赠品" align="center" prop="isGift" :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <div v-for="(item, index) in scope.row.purchaseOrderProductList" :key="index" class="item">
                            {{ item.isGift == 0 ? '否' : '是' }}
                            </div>
                        </template>
                        </el-table-column>
                        <el-table-column label="到货日期" align="center" prop="arrivalDate" :show-overflow-tooltip="true" width="150px">
                        <template slot-scope="scope">
                            <div v-for="(item, index) in scope.row.purchaseOrderProductList" :key="index" class="item">
                            {{ item.arrivalDate }}
                            </div>
                        </template>
                        </el-table-column>
                        <el-table-column label="关联申请单号" align="center" prop="requisitionNumber" :show-overflow-tooltip="true" width="150px">
                        <template slot-scope="scope">
                            <div v-for="(item, index) in scope.row.purchaseOrderProductList" :key="index" class="item">
                            {{ item.requisitionNumber }}
                            </div>
                        </template>
                        </el-table-column>
                        <el-table-column label="实际入库" align="center" prop="warehouseCount" :show-overflow-tooltip="true">
                        <template slot-scope="scope">
                            <div v-for="(item, index) in scope.row.purchaseOrderProductList" :key="index" class="item">
                            {{ item.warehouseCount }}
                            </div>
                        </template>
                        </el-table-column>
                        <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" width="150px" />
                    </el-table>
                    <pagination
                        v-show="total > 0"
                        :total="total"
                        :page.sync="queryParams.pageNum"
                        :limit.sync="queryParams.pageSize"
                        @pagination="getPurchaseOrderList"
                    />
                </el-col>
            </el-row>
        </el-dialog>
    </div>
</template>

<script>
import { returnAdd, returnEdit, returnDetail, returnProduct, returnProductOrder } from "@/api/system/purchaseReturn/purchaseReturn"
import { listSupplier, listProduct } from "@/api/system/basicdata/basicdata"
import { skuListStock } from "@/api/system/stock/stock"
export default {
    name: "add",
    data() {
        return {
            id: '',
            form: {
                code: '', // 采购退货编码
                businessDate: '', // 业务日期
                supplierInfoId: '', // 供应商id
                supplierCode: '', // 供应商编码
                supplierName: '', // 供应商名称
                returnDate: '', // 要求退货日期
                businessModel: '0', // 业务模式
                businessUnit: '', // 业务部门
                haveOrNot: '1', // 是否有源单
                allOrNot: '1', // 是否全退
                purchaseOrderId: '', // 源采购订单id
                purchaseOrderCode: '', // 源采购订单
                reasonForReturn: '', // 退货原因
                invoiceType: '1', // 发票类型
                remark: '', // 备注
                purchaseReturnOrderDetailList: [], // 商品数据
                totalNum: '', // 合计数量
                totalAmount: '', // 合计未税金额
                totalTaxAmount: '', // 合计价税合计
                createBy: '', // 创建人
                createTime: '', // 创建日期
                approvalBy: '', // 审核人
                approvalTime: '', // 审核日期
            },
            show: false,
            supplierList: [], // 供应商列表
            // 税率
            businessUnitList: [], // 业务部门列表
            purchaseOrderList: [], // 源采购订单列表
            searchProductList: [], // 产品列表数据
            // 表头
            columns: [{
                prop: "productBasicCode",
                label: "产品编码",
                width: 160,
                type: '1'
            },{
                prop: "productBasicName",
                label: "产品名称",
                width: 160,
                type: '2'
            },{
                prop: "specificationCode",
                label: "SKU编码",
                width: 250,
                type: '1'
            },{
                prop: "specificationName",
                label: "SKU名称",
                width: 250,
                type: '2'
            },{
                prop: "productShortName",
                label: "简称",
                type: '3'
            },{
                prop: "specification",
                label: "规格",
                type: '3'
            },
            // {
            //     prop: "batchNumber",
            //     label: "批次",
            //     width: 150,
            //     type: 'batchNumber'
            // },
            {
                prop: "picksNum",
                label: "可退数量",
                width: 100,
                type: '3'
            },{
                prop: "planNum",
                label: "申退数量",
                width: 120,
                type: 'planNum'
            },{
                prop: "unit",
                label: "单位",
                width: 100,
                type: '3'
            },
            // {
            //     prop: "untaxedAmount",
            //     label: "未税金额",
            //     width: 100,
            //     type: '3'
            // },{
            //     prop: "taxRate",
            //     label: "税率",
            //     width: 100,
            //     type: '3'
            // },{
            //     prop: "levy",
            //     label: "税款",
            //     width: 100,
            //     type: '3'
            // },{
            //     prop: "totalTax",
            //     label: "价税合计",
            //     width: 100,
            //     type: '3'
            // },{
            //     prop: "isGift",
            //     label: "赠品",
            //     width: 100,
            //     type: 'isGift'
            // },{
            //     prop: "arrivalDate",
            //     label: "到货日期",
            //     width: 215,
            //     type: 'arrivalDate'
            // },{
            //     prop: "requisitionNumber",
            //     label: "关联申请单号",
            //     width: 100,
            //     type: '3'
            // },{
            //     prop: "warehouseOut",
            //     label: "实退出库",
            //     width: 100,
            //     type: '3'
            // },
            {
                prop: "remark",
                label: "备注",
                width: 100,
                type: 'remark'
            }],
            // 产品数据
            productData: [
                // {
                //     specificationId: '', // 产品id
                //     specificationCode: '', // 产品编码
                //     specificationName: '', // 产品名称
                //     productShortName: '', // 货品简称
                //     specification: '', // 规格
                //     batchNumber: '', // 批次
                //     picksNum: '', // 可退数量
                //     planNum: '', // 申退数量
                //     unit: '', // 单位
                //     untaxedUnitPrice: '', // 未税单价
                //     untaxedAmount: '', // 未税金额
                //     taxedUnitPrice: '', // 含税单价
                //     taxRate: '', // 税率
                //     levy: '', // 税款
                //     totalTax: '', // 价税合计
                //     isGift: '', // 赠品
                //     arrivalDate: '', // 到货日期
                //     requisitionNumber: '', // 关联申请单号
                //     warehouseOut: '', // 实退出库
                //     remark: '', // 备注
                // }
            ],
            // 日期控制
            pickerOptions: {
                // disabledDate(time) {
                //     return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
                // }
            },
            open: false, // 源采购订单弹窗
            queryPurchaseOrderList: [], // 源采购订单弹窗列表数据
            queryPurchaseOrderId: '',
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                supplierInfoId: undefined,
                searchValue: undefined,
                approvalStatus: 1
            },
            total: 0,
            taxRate: '', // 税率
            purchaseOrderBatch: [], // 批次
            queryType: ''
        }
    },
    created() {
        if(this.$route.query.supplier){
            this.form.supplierInfoId = this.$route.query.supplier.id
            this.form.supplierName = this.$route.query.supplier.name
            this.form.supplierCode = this.$route.query.supplier.supCode
            this.getReturnProduct(this.$route.query.supplier)
            this.$router.push({ query: {} })
        }
        if(this.$route.query.data){
            this.form = this.$route.query.form
            this.productData = this.$route.query.productData
            let data = this.$route.query.data
            this.queryType = 1
            this.getSkuListStock(data)
        }
        let userInfo = this.$store.state.user.users
        // console.log(userInfo)
        // this.form.businessUnit = userInfo.dept.deptId
        // 部门
        this.businessUnitList.push({
            deptId: userInfo.dept.deptId,
            deptName: userInfo.dept.deptName
        })
    },
    methods: {
        // 获取详情信息
        getDetailData() {
            returnDetail(this.id).then(res => {
                this.form = res.data
                if(res.data.purchaseReturnOrderDetailList == null){
                    this.productData = []
                }else{
                    res.data.purchaseReturnOrderDetailList.forEach(item => {
                        if(item.isGift == '1'){
                            item.isGift = true
                        }else{
                            item.isGift = false
                        }
                    })
                    this.productData = res.data.purchaseReturnOrderDetailList
                }
                if(this.form.haveOrNot !== '1'){
                    this.addProduct()
                }
            })
        },
        // 供应商搜索
        onChangeSupplier(val){
            if(val !== ''){
                this.show = true
                // 查询供应商列表
                listSupplier({ searchValue: val, status: 1, approveStatus: 1 }).then(res => {
                    this.supplierList = res.rows
                })
            }else{
                this.form.supplierInfoId = ''
                this.form.supplierName = ''
                this.show = false
            }
        },
        // 选中供应商
        check(item) {
            this.form.supplierInfoId = item.id
            this.form.supplierName = item.name
            this.form.supplierCode = item.supCode
            this.taxRate = item.shareInvoice == null ? '0' : item.shareInvoice.taxpayerScale == '0' ? '16%' : item.shareInvoice.taxpayerScale == '1' ? '13%' : item.shareInvoice.taxpayerScale == '2' ? '6%' : item.shareInvoice.taxpayerScale == '3' ? '3%' : '0'
            this.show = false
            this.queryPurchaseOrderId = item.id
            this.getReturnProduct(item)
        },
        // 供应商弹窗
        onSupplierList(){
            this.$router.push({path:"/basicData/supplier", query:{ type: 'purchaseReturnAdd' }})
        },
        // 根据供应商获取源采购订单
        getReturnProduct(item){
            returnProduct({supplierInfoId: item.id}).then(res => {
                this.purchaseOrderList = res.rows
            })
        },
        // 是否有源单 1是 0否
        onChangeIs(val){
            this.form.purchaseOrderId = ''
            this.form.purchaseOrderCode = ''
            this.form.totalNum = ''
            this.form.totalAmount = ''
            this.productData = []
            if(val == '1'){
                this.form.allOrNot = '1'
                this.searchProductList = []
            }else{
                this.form.allOrNot = ''
                this.addProduct()
                listProduct().then(res => {
                    if(res.code == 200){
                        this.searchProductList = res.rows
                    }
                })
            }
        },
        // 是否全退 1是 0否
        onChangeIsAllReturn(val){
            this.form.totalNum = ''
            this.form.totalAmount = ''
            this.productData = []
            if(this.form.purchaseOrderId !== '' || this.form.purchaseOrderId !== null || this.form.purchaseOrderId !== undefined){
                if(val == '1'){
                    returnProductOrder({ id: this.form.purchaseOrderId }).then(res => {
                        this.productData = res.data
                        this.totalData()
                        // this.form.totalNum = this.purchaseOrderList[0].totalNum
                        // this.form.totalAmount = this.purchaseOrderList[0].totalAmount
                    })
                }else{
                    this.addProduct()
                    returnProduct({ id: this.form.purchaseOrderId }).then(res => {
                        if(res.code == 200){
                            this.searchProductList = res.rows[0].purchaseOrderProductList
                        }
                    })
                }
            }
        },
        // 选择源采购订单
        onChangePurchaseOrder(val){
            if(this.form.supplierInfoId == '' || this.form.supplierInfoId == null || this.form.supplierInfoId == undefined){
                this.$modal.msgError('供应商不能为空！')
                this.form.purchaseOrderId = ''
                this.form.purchaseOrderCode = ''
            }else{
                let purchaseOrder = this.purchaseOrderList.find(item => item.purchaseOrderCode == val)
                this.form.purchaseOrderId = purchaseOrder.id
                // this.form.totalNum = purchaseOrder.totalNum
                // this.form.totalAmount = purchaseOrder.totalAmount
                if(this.form.allOrNot == '1'){
                    // 根据源采购订单查询全退产品
                    returnProductOrder({ id: purchaseOrder.id }).then(res => {
                        res.data.forEach(item => {
                            if(item.planNum == 0){
                                item.planNum = ''
                            }
                            if(item.isGift == '1'){
                                item.isGift = true
                            }else{
                                item.isGift = false
                            }
                        })
                        this.productData = res.data
                        this.totalData()
                    })
                }else{
                    this.form.totalNum = ''
                    this.form.totalAmount = ''
                    this.searchProductList = purchaseOrder.purchaseOrderProductList
                }
            }
        },
        // 跳转采购订单列表
        onPurchaseOrderList(){
            if(this.form.supplierInfoId == '' || this.form.supplierInfoId == null || this.form.supplierInfoId == undefined){
                this.$modal.msgError('供应商不能为空！')
            }else{
                this.open = true
                this.getPurchaseOrderList()
            }
        },
        // 源采购订单
        getPurchaseOrderList(){
            this.queryParams.supplierInfoId = this.queryPurchaseOrderId
            returnProduct(this.addDateRange(this.queryParams)).then(res => {
                this.queryPurchaseOrderList = res.rows
                this.total = res.total
            })
        },
        // 搜索按钮
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getPurchaseOrderList()
        },
        // 重置按钮
        resetQuery() {
            this.resetForm("queryForm")
            this.handleQuery()
        },
        // 选中采购订单
        onClickPurchaseOrderList(row){
            // console.log(row, '111')
            // 数据属性名转换
            let data = row.purchaseOrderProductList.map(item => {
                return {
                    productBasicId: item.productBasicId,
                    productBasicCode: item.productBasicCode,
                    productBasicName: item.productBasicName,
                    specificationId: item.productId, // 产品id
                    specificationCode: item.productCode, // 产品编码
                    specificationName: item.productName, // 产品名称
                    productShortName: item.productShortName, // 货品简称
                    specification: item.specification, // 规格
                    batchNumber: item.batch, // 批次
                    picksNum: item.warehouseCount - item.returnCount, // 可退数量
                    planNum: item.picksNum == 0 ? '' :  item.picksNum, // 申退数量
                    unit: item.unit, // 单位
                    untaxedUnitPrice: item.untaxedAmount, // 未税单价
                    untaxedAmount: 0, // 未税金额
                    taxedUnitPrice: 0, // 含税单价
                    taxRate: item.taxRate, // 税率
                    levy: item.levy, // 税款
                    totalTax: item.totalTax, // 价税合计
                    isGift: item.isGift == '1' ? true : false, // 赠品
                    arrivalDate: item.arrivalDate, // 到货日期
                    remark: item.remark // 备注
                }
            })
            this.productData = data
            this.form.purchaseOrderCode = row.purchaseOrderCode
            this.form.purchaseOrderId = row.id
            this.open = false
        },
        // 新建产品数据
        addProduct(){
            let data = {
                key: {
                    specificationId: ''
                }
            }
            this.columns.forEach(item =>{
                data.key[item.prop] = ''
            })
            this.productData.push(JSON.parse(JSON.stringify(data.key)))
        },
        // 有源单产品编码搜索
        searchCode(val, cb) {
            let list = []
            this.searchProductList.map(item => {
                list.push(Object.assign(
                    {},item,{
                        value: item.productCode
                    }
                ))
            })
            var arr = list
            var results = val ? arr.filter(this.createFilter(val)) : arr
            cb(results)
        },
        // 无源单产品编码搜索
        searchProductCode(val, cb) {
            let list = []
            this.searchProductList.map(item => {
                list.push(Object.assign(
                    {},item,{
                        value: item.specificationCode
                    }
                ))
            })
            var arr = list
            var results = val ? arr.filter(this.createFilter(val)) : arr
            cb(results)
        },
        // 有源单产品名称搜索
        searchName(val, cb){
            let list = []
            this.searchProductList.map(item => {
                list.push(Object.assign(
                    {},item,{
                        value: item.productName
                    }
                ))
            })
            var arr = list
            var results = val ? arr.filter(this.createFilter(val)) : arr
            cb(results)
        },
        // 无源单产品名称搜索
        searchProductName(val, cb){
            let list = []
            this.searchProductList.map(item => {
                list.push(Object.assign(
                    {},item,{
                        value: item.specificationName
                    }
                ))
            })
            var arr = list
            var results = val ? arr.filter(this.createFilter(val)) : arr
            cb(results)
        },
        // 匹配
        createFilter(val) {
            return (res) => {
                return (res.value.toLowerCase().indexOf(val.toLowerCase()) === 0)
            }
        },
        // 选中产品
        handleSelect(item, row, index){
            if(this.form.supplierInfoId == '' || this.form.supplierInfoId == null || this.form.supplierInfoId == undefined){
                this.$modal.msgError('供应商不能为空！')
                this.productData = []
                this.addProduct()
            }else{
                // 是否有源单 1是 0否
                if(this.form.haveOrNot == '1'){
                    if(this.form.purchaseOrderCode == '' || this.form.purchaseOrderCode == null || this.form.purchaseOrderCode == undefined){
                        this.$modal.msgError('源采购订单不能为空！')
                        this.productData = []
                        this.addProduct()
                    }else{
                        // 是否全退 1是 0否
                        if(this.form.allOrNot == '0'){
                            this.productField(item, row, index)
                        }
                    }
                }else{
                    this.productField(item, row, index)
                }
            }
        },
        // 产品字段
        productField(item, row, index){
            if(this.form.haveOrNot == '1'){
                row.productBasicId = item.productBasicId
                row.productBasicCode = item.productBasicCode
                row.productBasicName = item.productBasicName
                row.specificationId = item.productId // 产品id
                row.specificationCode = item.productCode // 产品编码
                row.specificationName = item.productName // 产品名称
                row.productShortName = item.productShortName // 货品简称
                row.specification = item.specification // 规格
                row.batchNumber = item.batch // 批次
                row.picksNum = item.warehouseCount - item.returnCount// 可退数量
                row.planNum = row.picksNum == 0 ? '' : row.picksNum // 申退数量
                row.unit = item.unit // 单位
                row.untaxedUnitPrice = item.untaxedAmount // 未税单价
                row.untaxedAmount = item.amount // 未税金额
                row.taxedUnitPrice = item.taxUnitPrice // 含税单价
                row.taxRate = item.taxRate // 税率
                row.levy = item.levy // 税款
                row.totalTax = item.totalTax // 价税合计
                row.isGift = item.isGift == '1' ? true : false // 赠品
                row.arrivalDate = item.arrivalDate // 到货日期
                row.remark = item.remark // 备注
                // 过滤已选择的产品
                let filterProductList = this.searchProductList.filter(item => item.productId !== row.specificationId)
                this.searchProductList = filterProductList
                // 插入已选择产品
                let arr = this.productData.filter(item => item.specificationCode !== '')
                if(arr && arr.length > 0){
                    this.productData = arr
                    if(filterProductList.length > 0){
                        this.addProduct()
                    }
                    this.totalData()
                }
            }else{
                this.getSkuListStock(item, row)
            }
        },
        // 查询库存
        getSkuListStock(item, row){
            skuListStock({ specificationId: item.productSpecificationsId }).then(res => {
                if(res.rows.length > 0){
                    if(this.queryType == 1){
                        let str = this.taxRate.substring(0, this.taxRate.lastIndexOf('%'))
                        let price = item.purchasePrice !== null ? item.purchasePrice : 0
                        let obj = {}
                        if(item.priceType == '1'){
                            obj = {
                                productBasicId: item.productBasicId,
                                productBasicCode: item.productBasicCode,
                                productBasicName: item.productBasicName,
                                specificationId: item.productSpecificationsId,
                                specificationCode: item.specificationCode,
                                specificationName: item.specificationName,
                                productShortName: item.shortName,
                                specification: item.value1 + item.value2,
                                enableBatches: item.enableBatches,
                                planNum: '',
                                unit: item.unit,
                                untaxedUnitPrice: (price / (1 + (Number(str) / 100))).toFixed(2),
                                taxRate: this.taxRate,
                                taxedUnitPrice: price,
                                isGift: false,
                            }
                        }else{
                            obj = {
                                productBasicId: item.productBasicId,
                                productBasicCode: item.productBasicCode,
                                productBasicName: item.productBasicName,
                                specificationId: item.productSpecificationsId,
                                specificationCode: item.specificationCode,
                                specificationName: item.specificationName,
                                productShortName: item.shortName,
                                specification: item.value1 + item.value2,
                                enableBatches: item.enableBatches,
                                planNum: '',
                                unit: item.unit,
                                untaxedUnitPrice: price,
                                taxRate: this.taxRate,
                                taxedUnitPrice: (price * (1 + (Number(str) / 100))).toFixed(2),
                                isGift: false,
                            }
                        }
                        if(this.productData.length == 0){
                            this.productData.push(obj)
                            this.$router.push({ query: {} })
                        }else{
                            let index = this.productData.findIndex(i => i.specificationCode == item.specificationCode)
                            if(index > -1){
                                this.$modal.msgError('产品已存在，请重新选择！')
                                this.$router.push({ query: {} })
                            }else{
                                this.productData.push(obj)
                                this.$router.push({ query: {} })
                            }
                        }
                        let arr = this.productData.filter(i => i.specificationCode !== '')
                        this.productData = arr
                    }else{
                        row.productBasicId = item.productBasicId
                        row.productBasicCode = item.productBasicCode
                        row.productBasicName = item.productBasicName
                        row.specificationId = item.productSpecificationsId // 产品id
                        row.specificationCode = item.specificationCode // 产品编码
                        row.specificationName = item.specificationName // 产品名称
                        row.productShortName = item.shortName // 货品简称
                        row.specification = item.value1 + item.value2 // 规格
                        row.enableBatches = item.enableBatches // 是否启用批次
                        row.planNum = '' // 申退数量
                        row.unit = item.unit // 单位
                        row.taxRate = this.taxRate // 税率
                        let str = this.taxRate.substring(0, this.taxRate.lastIndexOf('%'))
                        if(item.priceType == '1'){
                            row.taxedUnitPrice = item.purchasePrice !== null ? item.purchasePrice : 0 // 含税单价
                            row.untaxedUnitPrice = (row.taxedUnitPrice / (1 + (Number(str) / 100))).toFixed(2) // 未税单价
                        }else{
                            row.untaxedUnitPrice = item.purchasePrice !== null ? item.purchasePrice : 0 // 未税单价
                            row.taxedUnitPrice = (row.untaxedUnitPrice * (1 + (Number(str) / 100))).toFixed(2) // 含税单价
                        }
                        row.isGift = false // 赠品
                        // 过滤已选择的产品
                        let filterProductList = this.searchProductList.filter(item => item.productSpecificationsId !== row.specificationId)
                        this.searchProductList = filterProductList
                    }
                    this.addProduct()
                    if(item.enableBatches == '1'){
                        row.picksNum = res.rows[0].store
                    }else{
                        this.purchaseOrderBatch = res.rows
                    }
                }else{
                    if(this.queryType !== 1){
                        row.specificationCode = '' // 产品编码
                        row.specificationName = '' // 产品名称
                    }else{
                        this.$router.push({ query: {} })
                    }
                    this.$modal.msgError('暂无库存!')
                }
            })
        },
        // 选择批次
        onChangeBatch(item, row){
            let data = this.purchaseOrderBatch.find(i => i.batchNumber == item)
            row.picksNum = data.store
        },
        // 跳转sku列表
        searchProductSku(){
            let arr = this.productData.filter(item => item.specificationCode !== '')
            this.$router.push({path:"/basicData/product/sortList", query:{ type: 'purchaseReturnAdd', form: this.form, productData: arr }})
        },
        // 数量验证
        inputNum(val, row){
            // console.log(row)
            if(val == '' || val == undefined){
                this.$modal.msgError('申退数量不能为空!')
                row.planNum = ''
                // row.totalTax = ''
                // row.levy = ''
                this.form.totalNum = ''
                this.form.totalAmount = ''
                this.form.totalTaxAmount = ''
            }else{
                if(/^[1-9]\d*$|^0$/.test(val) == false){
                    this.$modal.msgError('申退数量必须是数字！')
                    row.planNum = ''
                    this.form.totalNum = ''
                    this.form.totalAmount = ''
                    this.form.totalTaxAmount = ''
                    return false
                }else{
                    if(JSON.parse(val) <= 0){
                        this.$modal.msgError('申退数量必须大于0!')
                        row.planNum = ''
                    }else{
                        if(JSON.parse(val) > row.picksNum){
                            row.planNum = ''
                            // row.totalTax = ''
                            // row.levy = ''
                            this.form.totalNum = ''
                            this.form.totalAmount = ''
                            this.form.totalTaxAmount = ''
                            this.$modal.msgError('申退数量不能大于可退数量!')
                        }else{
                            // 判断是否有源单
                            if(this.form.haveOrNot == 1){
                                // row.untaxedAmount = (row.planNum * row.untaxedUnitPrice).toFixed(2) // 未税金额
                                // row.totalTax = (row.planNum * row.taxedUnitPrice).toFixed(2) // 价税合计
                                // row.levy = (row.totalTax - row.untaxedAmount).toFixed(2) // 税款
                                this.totalData()
                            }else{
                                row.untaxedAmount = (row.planNum * row.untaxedUnitPrice).toFixed(2) // 未税金额
                                row.totalTax = (row.planNum * row.taxedUnitPrice).toFixed(2) // 价税合计
                                row.levy = (row.totalTax - row.untaxedAmount).toFixed(2) // 税款
                                this.totalData()
                            }
                        }
                    }
                }
            }
        },
        // 合计
        totalData(){
            let totalNum = 0
            let totalAmount = 0
            let totalTaxAmount = 0
            let arr = this.productData.filter(item => item.specificationCode !== '')
            arr.forEach(item => {
                totalNum += Number(item.planNum)
                totalAmount += Number(item.planNum) * Number(item.untaxedUnitPrice)
                totalTaxAmount += Number(item.planNum) * Number(item.taxedUnitPrice)
                return (totalNum, totalAmount, totalTaxAmount)
            })
            this.form.totalNum = totalNum
            this.form.totalAmount = totalAmount.toFixed(2)
            this.form.totalTaxAmount = totalTaxAmount.toFixed(2)
        },
        // 保存/提交
        submitForm(e){
            let arr = this.productData.filter(item => item.specificationCode !== '')
            // 是否赠品
            arr.forEach(item => {
                if(item.isGift == true){
                    item.isGift = 1
                }else{
                    item.isGift = 0
                }
            })
            let planNum = arr.every(val => !!val.planNum)
            // console.log(arr)
            this.form.purchaseReturnOrderDetailList = arr
            if(e == 'save'){
                // 保存
                if(this.id){
                    let data = this.form
                    data.id = this.id
                    this.$modal.loading("正在保存")
                    returnEdit(data).then(res=> {
                        if(res.code == 200){
                            this.getDetailData()
                            this.$modal.msgSuccess("保存成功")
                            this.$modal.closeLoading()
                        }
                    })
                }else{
                    this.$modal.loading("正在保存")
                    returnAdd(this.form).then(res => {
                        if(res.code == 200){
                            this.id = res.data.id
                            this.getDetailData()
                            this.$modal.msgSuccess("保存成功")
                            this.$modal.closeLoading()
                        }
                    })
                }
            }else{
                if(arr.length > 0){
                    if(planNum == true){
                        // 提交
                        if(this.id){
                            let data = this.form
                            data.id = this.id
                            data.approvalStatus = 0
                            data.status = 1
                            this.$modal.loading("正在提交")
                            returnEdit(data).then(res=> {
                                if(res.code == 200){
                                    this.$refs.form.resetFields()
                                    this.$tab.closeOpenPage({ path: "/purchase/purchaseReturn/list" })
                                    this.$modal.msgSuccess("新建成功")
                                    this.$modal.closeLoading()
                                }
                            })
                        }else{
                            let data = this.form
                            data.approvalStatus = 0
                            data.status = 1
                            this.$modal.loading("正在提交")
                            returnAdd(data).then(res=> {
                                if(res.code == 200){
                                    this.$refs.form.resetFields()
                                    this.$tab.closeOpenPage({ path: "/purchase/purchaseReturn/list" })
                                    this.$modal.msgSuccess("新建成功")
                                    this.$modal.closeLoading()
                                }
                            })
                        }
                    }else{
                        this.$modal.msgError('申退数量不能为空！')
                    }
                }else{
                    this.$modal.msgError('请选择产品！')
                }
            }
        }
    }
}
</script>


<style scoped>
.options {
    position: absolute;
    z-index:10;
    left:0;
    width: 82%;
}
.options li {
    height: 40px;
    line-height: 40px;
    cursor: pointer;
    border: 1px solid #DCDFE6;
    border-top: 0px;
    text-indent: 12px;
    overflow: hidden;
}
.options li:hover {
    background: #f3f5f9;
    color: #606266;
}
.options-item{
    background:#fff;
    overflow-y:scroll;
    max-height: 200px;
}
</style>
